package com.zcsy.manage.web.system;

import com.zcsy.manage.model.system.Menu;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.service.system.IMenuService;

@Controller
@RequestMapping(value = "/menubutton")
public class MenuButtonController {
	
	 private static final int BUTTON_ID = 0; //初始化新增id
	 private static final int BUTTON_ADD = 1; //跳转新增按钮页面type为1
	 private static final int BUTTON_EDIT = 2; //跳转新增按钮页面type为2
	 private static final int MENU_TYPE = 1; //1表示新增或编辑类型为菜单
	 private static final int BUTTON_TYPE = 2; //2表示新增或编辑类型为按钮
	@Autowired
	private IMenuService menuService;
	
	/**
	 * 
	 * @Description 返回功能管理页面<br>
	 * 
	 * @param model
	 * @param req 用户请求
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年5月10日
	 * @see
	 */
	@RequestMapping(value="menuButtonList" , method = RequestMethod.GET)
	public String categoryList(String id,Model model, HttpServletRequest req){
		return "system/menubutton/menuButtonList";
	}

	/**
	 * 
	 * @Description 生成功能管理树<br>
	 * 
	 * @param req
	 * @param response
	 * @return  返回功能管理json字符串
     *         {"id":菜单id,"pId":菜单上级id,"name":菜单名称}
	 * @author lilan 1063972142@qq.com
	 * @date 2016年5月10日
	 * @see
	 */
	 @RequestMapping(value="treeData" , method = RequestMethod.POST)
	    @ResponseBody
	    public RequestJson treeData(HttpServletRequest req,HttpServletResponse response,Integer system){
		 RequestJson result = new RequestJson();
	        JSONArray jsonArr=new JSONArray();
	        try {
	            List<Menu> list = menuService.getAllBySystem(system);
	            for(Menu item : list){
	            	JSONObject json = new JSONObject();
	            	json.put("id", item.getId());
	            	json.put("pId", item.getParentId());
	            	json.put("name", item.getMenuName());
	            	json.put("type", item.getType());
	            	jsonArr.add(json);
	            }
	            result.setObj(jsonArr.toJSONString());
	            System.out.println(jsonArr.toJSONString());
	        }catch (Exception e) {
	           e.printStackTrace();
	           result.setMsg("操作异常");
	           result.setSuccess(false);
	        }
	        return result;
	    }
	 
	 /**
	  * 
	  * @Description 根据主键id获取功能管理对象，返回功能管理详情<br>
	  * 
	  * @param id 主键id
	  * @param model
	  * @param req
	  * @return 
	  * @author lilan 1063972142@qq.com
	  * @date 2016年5月10日
	  * @see
	  */
	 @RequestMapping(value="menuButtonDetail" , method = RequestMethod.GET)
		@ResponseBody
		public Menu menuButtonDetail(String id,Model model, HttpServletRequest req){
			
			Menu menu = menuService.getMenuById(id);
			//判断该分类节点是否是叶子节点
//			goodsCategory.setLeaf(goodsCategoryService.isLeaf(id));
			
			return menu;
		}
	 
	 /**
	  * 
	  * @Description  根据角色获取数据列表
      * @param state  菜单状态
      * @param req 用户请求
	  * @return 
	  * @author lilan 1063972142@qq.com
	  * @date 2016年5月10日
	  * @see
	  */
	 @RequestMapping(value="updateMenuStateById" , method = RequestMethod.GET)
	    @ResponseBody
	    public RequestJson updateMenuStateById(String menuId,int state,HttpServletRequest req){
	        RequestJson result = new RequestJson();
	        
	        try {
	            menuService.updateMenuState(menuId, state);
	            
	            result.setSuccess(true);
	        }catch (Exception e) {
	           e.printStackTrace();
	           
	           result.setMsg("操作异常");
	           result.setSuccess(false);
	        }
	        
	        return result;
	    }
	 
	 /**
	  * 
	  * @Description 根据主键id查询菜单<br>
	  * 
	  * @param model
	  * @param id
	  * @return 
	  * @author lilan 1063972142@qq.com
	  * @date 2016年5月10日
	  * @see
	  */
	    @RequestMapping(value = "selectPK", method = RequestMethod.GET)
	    public String selectByPrimaryKey(Model model,@QueryParam("id") String id) {
	        try {
	            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
	                model.addAttribute("type", Constants.SAVE_TYPE);
	                Menu menu = new Menu();
	                short l = (short)(Constants.MENU_SELECT_NONE);
	                menu.setMenuLevel(l);
	                menu.setType(MENU_TYPE);
	                model.addAttribute("menu", menu);
	            } else {
	                Menu menu = menuService.getMenuById(id);
	                model.addAttribute("menu", menu);
	                Menu pmenu = menuService.getMenuById(menu.getParentId());
	                model.addAttribute("pMenu", pmenu);
	                Menu menuRecord = new Menu();
	                if(menu.getMenuLevel() == 2){
	                	 menuRecord.setMenuLevel((short)1);
	                }else if(menu.getMenuLevel() == 3){
	                	 menuRecord.setMenuLevel((short)2);
	                }
	                List<Menu> listMenu = menuService.queryMenu(menuRecord);
	                model.addAttribute("listMenu",listMenu);
	                model.addAttribute("type", Constants.EDIT_TYPE);
	            }
	            
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return "system/menubutton/menuButtonEdit";
	    }
	    
	    /**
	     * 
	     * @Description 新增或编辑菜单<br>
	     * 
	     * @param id 主键id
	     * @param mName 菜单名
	     * @param mLevel 菜单等级
	     * @param mURL 本地路径
	     * @param mOrder 菜单顺序
	     * @param mPId 父菜单id
	     * @param req 用户请求
	     * @return 
	     * @author lilan 1063972142@qq.com
	     * @date 2016年5月11日
	     * @see
	     */
	    @RequestMapping(value="editMenu" , method = RequestMethod.POST)
	    @ResponseBody
	    public RequestJson saveOrUpdateMenu(String id,String mName,Short mLevel,String mURL,Integer mOrder,String mPId,Integer system,Integer menuType,@Context HttpServletRequest req){
	        RequestJson result = new RequestJson();
	        Menu menuVo = new Menu();
	        menuVo.setType(MENU_TYPE);
	        menuVo.setMenuName(mName);
	        menuVo.setLocationURL(mURL);
	        menuVo.setMenuLevel(mLevel);
	        menuVo.setMenuOrder(mOrder);
	        menuVo.setParentId(mPId == null ? "0" : mPId);
	        menuVo.setSystem(system);
	        if(menuType != null){
	        	menuVo.setMenuType(menuType == 0 ? null : menuType);
	        }
	        
	        try {
	            if(id != null){
	            	menuVo.setId(id);
	                menuService.updateByPrimaryKey(menuVo);
	            }else{
	            	menuVo.setId(UniqueNumberUtils.get18UniqueNumber());
	                menuService.insert(menuVo);
	            }
	            result.setSuccess(true);
	        } catch (Exception e) {
	        	e.printStackTrace();
	            result.setMsg("操作失败");
	        }
	        return result;
	    }
	    
	    /**
	     * 
	     * @Description 获取级联菜单<br>
	     * 
	     * @param level 菜单等级
	     * @param req
	     * @return 
	     * @author lilan 1063972142@qq.com
	     * @date 2016年5月11日
	     * @see
	     */
	    @RequestMapping(value="getByLevel" , method = RequestMethod.GET)
	    @ResponseBody
	    public RequestJson getByLevel(Short level, Integer system, @Context HttpServletRequest req){
	        RequestJson result = new RequestJson();
	        Menu record = new Menu();
	        record.setMenuLevel(level); 
	        record.setSystem(system);
	        try {
	            List<Menu> menuList = menuService.queryMenu(record);
	            result.setObj(menuList);
	            result.setSuccess(true);
	        } catch (Exception e) {
	            e.printStackTrace();
	            result.setSuccess(false);
	        }
	        
	        return result;
	    }
	    
	    /**
	     * @Description 跳转新增或编辑页面<br>
	     * 
	     * @param model
	     * @param id 新增：id为0 编辑：id为当前记录id
	     * @return  返回新增或编辑页面
	     * @author lilan 1063972142@qq.com
	     * @date 2016年5月11日
	     * @see 
	     */
	    @RequestMapping(value = "buttonBox", method = RequestMethod.GET)
	    public String buttonBox(Model model,@QueryParam("id") String id) {
	        
	    	try {
	    		if(String.valueOf(BUTTON_ID).equals(id)){
	    			Menu button = new Menu();
	    			button.setType(BUTTON_TYPE);
	                model.addAttribute("type", BUTTON_ADD);
	                model.addAttribute("button", button);
	    		}else{
	    			Menu button = menuService.getMenuById(id);
	    			List<Menu> menus = menuService.getAllLeaves(button.getSystem());
	    			model.addAttribute("parentId", button.getParentId());
		            model.addAttribute("menus", menus);
	    			model.addAttribute("button",button);
	    			model.addAttribute("type", BUTTON_EDIT);
	    		}
			} catch (Exception e) {
				e.printStackTrace();
			}
	        return "system/menubutton/btnEdit";
	    }
	    
	    /** 
	     * @Title: getMenuLeavesBySystem 
	     * @Description: 根据系统查询下属所有叶子菜单
	     * @param @param system 系统
	     * @param @param req 请求
	     * @param @return     
	     * @return RequestJson    返回 
	     * @throws 
	     */
	    @RequestMapping(value="getMenuLeavesBySystem" , method = RequestMethod.GET)
	    @ResponseBody
	    public RequestJson getMenuLeavesBySystem(Integer system, @Context HttpServletRequest req){
	        RequestJson result = new RequestJson();
	        try {
	        	List<Menu> menus = menuService.getAllLeaves(system);
	            result.setObj(menus);
	            result.setSuccess(true);
	        } catch (Exception e) {
	            e.printStackTrace();
	            result.setSuccess(false);
	        }
	        
	        return result;
	    }
	    
	    /**
	     * 
	     * @Description 编辑或新增按钮<br>
	     * 
	     * @param mkey 菜单名
	     * @param bvalue 按钮值
	     * @param id 主键id
	     * @param req 用户请求
	     * @return 
	     * @author lilan 1063972142@qq.com
	     * @date 2016年5月11日
	     * @see
	     */
	    @RequestMapping(value="editBtn" , method = RequestMethod.POST)
	    @ResponseBody
	    public RequestJson saveOrUpdateBtn(String menuName,String bvalue,String id,String parentId, Integer system, HttpServletRequest req){
	        RequestJson result = new RequestJson();
	        Menu btn = new Menu();
	        btn.setMenuName(menuName);
	        btn.setValue(bvalue);
	        btn.setParentId(parentId);
	        btn.setType(BUTTON_TYPE);
	        btn.setSystem(system);
	       
	        try {
	            if(!String.valueOf(BUTTON_ID).equals(id)){
	            	btn.setId(id);
	            	menuService.updateByPrimaryKey(btn);
	            }else{
	            	btn.setId(UniqueNumberUtils.get18UniqueNumber());
	            	menuService.insert(btn);
	            }
	            result.setSuccess(true);
	        } catch (Exception e) {
	        	e.printStackTrace();
	            result.setMsg("操作失败");
	        }
	        return result;
	    }
	    
	   
	    
}
